package cn.iocoder.yudao.module.trade.service.delivery;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.ip.core.Area;
import cn.iocoder.yudao.framework.ip.core.enums.AreaTypeEnum;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.module.system.api.wechat_card.WeChatCardApi;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.wxexpress.ExpressChannelReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.wxexpress.ExpressCreateReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.wxexpress.ExpressGetInfoReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.wxexpress.ExpressUpdatePrinter;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemOtherDO;
import cn.iocoder.yudao.module.trade.framework.delivery.core.client.convert.WxExpressConvert;
import cn.iocoder.yudao.module.trade.framework.delivery.core.client.dto.wxexpress.WxExpressCreateDTO;
import cn.iocoder.yudao.module.trade.framework.delivery.core.client.dto.wxexpress.wxExpressCreate.GoodsDetailDTO;
import cn.iocoder.yudao.module.trade.framework.delivery.core.client.dto.wxexpress.wxExpressCreate.ReceiverDTO;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderQueryService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mchange.lang.LongUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
@Slf4j
@Validated
public class WxExpressServiceImpl implements WxExpressService {

    @Resource
    private TradeOrderQueryService tradeOrderQueryService;
    @Resource
    private WeChatCardApi weChatCardApi;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private ObjectMapper objectMapper;

    //生成面单
    private static final String EXPRESS_ORDER_ADD = "https://api.weixin.qq.com/cgi-bin/express/business/order/add";

    //取消运单
    private static final String EXPRESS_ORDER_CANCEL = "https://api.weixin.qq.com/cgi-bin/express/business/order/add";

    //获取运单数据
    private static final String EXPRESS_GET_ORDER = "https://api.weixin.qq.com/cgi-bin/express/business/order/get";

    //配置面单打印员
    private static final String UPDATE_EXPRESS_PRINTER = "https://api.weixin.qq.com/cgi-bin/express/business/printer/update";

    //获取打印员
    private static final String GET_EXPRESS_PRINTER = "https://api.weixin.qq.com/cgi-bin/express/business/printer/getall";

    //获取支持的快递公司列表
    private static final String GET_EXPRESS_DELIVERY = "https://api.weixin.qq.com/cgi-bin/express/business/delivery/getall";


    @Override
    public Boolean createExpressOrder(ExpressCreateReqVO reqVO) {
        try {
//            String accessToken = weChatCardApi.getAccessToken();
//            String url = EXPRESS_ORDER_ADD + "?access_token=" + accessToken;

        }catch (Exception e){
            e.printStackTrace();
        }


//        System.err.println("params:" + params);
//        String result = HttpUtil.post(url, params);
//        JSONObject resultObj = JSON.parseObject(result);
//        Integer errcode = resultObj.getInteger("errcode");
//        if (errcode != 0) {
//            String errmsg = resultObj.getString("errmsg");
//            log.info("微信物流服务-生成订单异常:{}", errmsg);
//            return false;
//        }
        return true;
    }

    @Override
    public Boolean channelExpressOrder(ExpressChannelReqVO reqVO) {
        try{
            String url = EXPRESS_ORDER_CANCEL + "?access_token=" + weChatCardApi.getAccessToken();
            String params = objectMapper.writeValueAsString(reqVO);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(params, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            String result = exchange.getBody();

            if (StringUtils.isNotEmpty(result)){
                JSONObject resultObj = JSON.parseObject(result);
                Integer errcode = resultObj.getInteger("errcode");
                if (errcode != 0) {
                    log.info("微信物流服务-取消订单异常:{}", resultObj.getString("errmsg"));
                    return false;
                }
                log.info("微信物流服务-取消订单返回数据:{}",resultObj);
                return true;
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public JSONObject getExpressOrder(ExpressGetInfoReqVO reqVO) {
        String url = EXPRESS_GET_ORDER + "?access_token=" + weChatCardApi.getAccessToken();
        try {
            String params = objectMapper.writeValueAsString(reqVO);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(params, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            String result = exchange.getBody();
            if (StringUtils.isNotBlank(result)) {
                JSONObject resultObj = JSON.parseObject(result);
                if (ObjectUtil.isNotEmpty(resultObj.getInteger("errcode"))) {
                    log.info("微信物流服务-查询订单异常:{}", resultObj.getString("errmsg"));
                    return null;
                }
                return resultObj;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }



    @Override
    public Boolean updateExpressPrinter(ExpressUpdatePrinter reqVO) {
        String url = UPDATE_EXPRESS_PRINTER + "?access_token=" + weChatCardApi.getAccessToken();
        try {
            String params = objectMapper.writeValueAsString(reqVO);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(params, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            String result = exchange.getBody();
            if (StringUtils.isNotBlank(result)) {
                JSONObject resultObj = JSON.parseObject(result);
                if (ObjectUtil.isNotEmpty(resultObj.getInteger("errcode"))) {
                    log.info("微信物流服务-配置面单打印员异常:{}", resultObj.getString("errmsg"));
                    return false;
                }
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public JSONObject getExpressPrinter() {
        String url = GET_EXPRESS_PRINTER + "?access_token=" + weChatCardApi.getAccessToken();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String result = exchange.getBody();
        if (StringUtils.isNotBlank(result)) {
            JSONObject resultObj = JSON.parseObject(result);
            if (ObjectUtil.isNotEmpty(resultObj.getInteger("errcode"))) {
                log.info("微信物流服务-获取打印员异常:{}", resultObj.getString("errmsg"));
                return null;
            }
            return resultObj;
        }
        return null;
    }

    @Override
    public JSONObject getAllDelivery() {
        String url = GET_EXPRESS_DELIVERY + "?access_token=" + weChatCardApi.getAccessToken();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String result = exchange.getBody();
        if (StringUtils.isNotBlank(result)) {
            JSONObject resultObj = JSON.parseObject(result);
            if (ObjectUtil.isNotEmpty(resultObj.getInteger("errcode"))) {
                log.info("微信物流服务-获取支持的快递公司列表:{}", resultObj.getString("errmsg"));
                return null;
            }
            return resultObj;
        }
        return null;
    }


}
